package com.bookstore.spring.util;


import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * Created by Admin on 2016/8/4.
 */
public class JdbcUtils {
    public static JdbcUtils jdbcUtils = null;

    static {
        jdbcUtils = new JdbcUtils();
    }

    /**
     * 释放资源
     *
     * @param connection
     */
    public static void release(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void release(ResultSet resultSet, Statement statement) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public Connection getConnection() throws Exception {
        Properties properties = new Properties();
        InputStream in =
                getClass().getClassLoader().getResourceAsStream("jdbc.properties");
        properties.load(in);
        String driver = properties.getProperty("driver");
        String user = properties.getProperty("username");
        String jdbcUrl = properties.getProperty("url");
        String password = properties.getProperty("password");
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
        return connection;
    }

}
